const key = 'search_history'

Page({
    data: {
        recentSearches: wx.getStorageSync(key) as string[]||['手机', '电脑', '运动鞋'],
        hotSearches: ['智能手表', '无线耳机', '平板电脑'],
        keyword: '',
        isShowDelete: true
    },
    //搜索
    onSearch() {
        //非空
        if (this.data.keyword.trim() === '') {
            wx.showToast({ title: '请输入商品名称', icon: 'error' })
            return
        }
        //获取最近搜索列表
        const list = this.data.recentSearches
        //查询是否重复
        if (list.includes(this.data.keyword)) {
            const index = list.findIndex(v => v === this.data.keyword)
            list.splice(index, 1)
        }
        if (list.length >= 5) {
            list.pop()
        }
        list.unshift(this.data.keyword)
        this.setData({
            recentSearches: list,
            keyword: ''
        })
        wx.setStorageSync('key',list)
    },
    //切换显示与隐藏
    toggleShowDelete() {
        this.setData({
            isShowDelete: !this.data.isShowDelete
        })
    },
    //全部删除
    clearList() {
        this.setData({
            recentSearches: [],
            isShowDelete: false
        })
        // wx.setStorageSync('key',[])
        wx.setStorageSync('key',this.data.recentSearches)
    },
    //删其中一个
    deleteItem(event: WechatMiniprogram.BaseEvent) {
        const list = this.data.recentSearches
        list.splice(event.currentTarget.dataset.index, 1)
        this.setData({
            recentSearches: list
        })
        wx.setStorageSync('key',this.data.recentSearches)

        if (list.length === 0) {
            this.setData({
                isShowDelete: false
            })
        }
    }
})